import React, { Component } from "react";
import { Flex, WingBlank, WhiteSpace, Toast } from "antd-mobile";

import { Link } from "react-router-dom";

import NavHeader from "../../components/NavHeader";

import styles from "./index.module.css";

import { withFormik, Form, Field, ErrorMessage } from "formik";

import { API } from "../../utils";

import * as Yup from "yup";

// 验证规则
const REG_UNAME = /^[a-zA-Z_\d]{5,8}$/;
const REG_PWD = /^[a-zA-Z_\d]{5,12}$/;
/**
 * 简化表单处理
 *
 * 1 导入 Form 组件, 替换 form 元素,去掉 onSubmit
 * 2 导入 Field 组件 , 替换 input 表单元素,去掉 onChange 、 onBlur 、value
 * 3 导入 ErrorMessage 组件，原来的错误消息逻辑代码
 * 4 去掉所有的props
 */
class Login extends Component {
  render() {
    // 通过 props 获取高阶组件传递过来的属性
    const { handleSubmit } = this.props;
    return (
      <div className={styles.root}>
        {/* 顶部导航 */}
        <NavHeader className={styles.navHeader}>账号登录</NavHeader>
        <WhiteSpace size="xl" />

        {/* 登录表单 */}
        <WingBlank>
          <Form>
            <div className={styles.formItem}>
              <Field
                name="username"
                className={styles.input}
                autoComplete="off"
                placeholder="请输入账号"
              />
            </div>
            <ErrorMessage
              name="username"
              component="div"
              className={styles.error}
            />

            <div className={styles.formItem}>
              <Field
                name="password"
                type="password"
                placeholder="请输入密码"
                className={styles.input}
              />
            </div>
            <ErrorMessage
              name="password"
              component="div"
              className={styles.error}
            />

            <div className={styles.formSubmit}>
              <button
                className={styles.submit}
                onClick={handleSubmit}
                type="button"
              >
                登 录
              </button>
            </div>
          </Form>
          <Flex className={styles.backHome}>
            <Flex.Item>
              <Link to="/registe">还没有账号,去注册~</Link>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    );
  }
}

Login = withFormik({
  // 提供状态
  mapPropsToValues: () => ({
    username: "",
    password: "",
  }),
  // 表单的提交事件
  handleSubmit: async (values, { props }) => {
    const { username, password } = values;
    const res = await API.post(`/user/login`, {
      username,
      password,
    });
    const { status, body, description } = res.data;
    if (status === 200) {
      /**
       * 登录成功
       * 1 判断是否需要跳转到用户想访问的页面(判断props.location.state 是否有值)
       * 2 没有跳到上一个页面 ,history.go(-1)
       * 3 有,跳转到 from.pathname 指定页面 (推荐使用replace方法模式,而不是push,因为push会后跳转到指定页面,返回上一个页面还是会回到登录页)
       */
      localStorage.setItem("hkzf_token", body.token);

      // 注意:无法通过 this 拿到路由信息
      // 通过第二个参数对象拿到 props
      if (props.location.state) {
        const pathname = props.location.state.from.pathname;

        /**
         * 路由历史记录 push:[home,login,map]
         *         replace:[home,map]
         */
        if (pathname.startsWith("/detail")) {
          return props.history.go(-1);
        }
        props.history.replace(pathname);
      } else {
        props.history.go(-1);
      }
    } else {
      Toast.info(description, 2, null, false);
    }
  },

  // 添加表单校验规则
  validationSchema: Yup.object().shape({
    username: Yup.string()
      .required("账号为必填项")
      .matches(REG_UNAME, "长度为5-8位,只能出现数字、字母、下划线"),
    password: Yup.string()
      .required("密码为必填项")
      .matches(REG_PWD, "长度为5-12位,只能出现数字、字母、下划线"),
  }),
})(Login);
export default Login;
